package com.xiang.xian.array;
import java.util.PriorityQueue;
/**
 * @Author Xiang.Xian
 * @Description
 * @Date 2025/01/09/21:56
 * @Version 1.0
 *
 * 无序数组找到第k大的数 ： 小根堆
 */


public class HeapSelect {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);

        for (int num : nums) {
            if (minHeap.size() < k) {
                minHeap.offer(num);
            } else if (num > minHeap.peek()) {
                minHeap.poll();
                minHeap.offer(num);
            }
        }
        return minHeap.peek();
    }

    public static void main(String[] args) {
        HeapSelect solution = new HeapSelect();
        int[] nums = {3, 2, 1, 5, 6, 4};
        int k = 2;
        System.out.println("The " + k + "th largest number is: " + solution.findKthLargest(nums, k));
    }
}
